package router

import (
	"context"
	"fmt"
	"gdshop-back-end-go/common/request/OrderReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-order/OrderService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/hprose/hprose-golang/rpc"
	"github.com/xxtea/xxtea-go/xxtea"
	"reflect"
)

func logInvokeHandler(
	name string,
	args []reflect.Value,
	context rpc.Context,
	next rpc.NextInvokeHandler) (results []reflect.Value, err error) {
	fmt.Printf("RPC进入 %s 参数 %v ---------------------------------------- \r\n", name, args)
	results, err = next(name, args, context)
	fmt.Printf("RPC结果 %v %v ---------------------------------------- \r\n", results, err)
	return
}

// 初始化 RPC 服务
func initRpcServer() {
	rpcService := rpc.NewHTTPService()
	rpcService.AddFunction("MemberCloseOrder", func(p *OrderReq.MemberCloseOrder) *response.JsonResponse {
		return OrderService.MemberCloseOrder(context.Background(), p)
	})
	rpcService.AddFunction("MemberConfirmOrder", func(p *OrderReq.MemberConfirmOrder) *response.JsonResponse {
		return OrderService.MemberConfirmOrder(context.Background(), p)
	})
	rpcService.AddFunction("MemberPay", func(p *OrderReq.MemberPay) *response.JsonResponse {
		return OrderService.MemberPay(context.Background(), p)
	})
	rpcService.AddFunction("ApiSendExpress", func(p *OrderReq.ApiSendExpress) *response.JsonResponse {
		return OrderService.ApiSendExpress(context.Background(), p)
	})
	rpcService.AddInvokeHandler(logInvokeHandler).
		AddBeforeFilterHandler(func(request []byte, context rpc.Context, next rpc.NextFilterHandler,
		) (response []byte, err error) {
			// 解密通讯
			response, err = next(xxtea.Decrypt(request, g.Cfg().GetBytes("server.rpc.Key")), context)
			return
		})
	//rpcService.Handle()
	rpcServer := g.Server("rpc")
	rpcServer.BindHandler("/rpc", func(r *ghttp.Request) {
		rpcService.ServeHTTP(r.Response.Writer, r.Request)
	})
	err := rpcServer.Start()
	if err != nil {
		panic(err)
	}
}
